//
//  MONoticeViewController.m
//  MobileOffice
//
//  Created by 晓 on 2019/5/30.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MONoticeViewController.h"
#import "MONoticeViewCell.h"
#import "MOWaitDoDetailViewController.h"
#import "MOFinishDoDetailViewController.h"
#import "MORefreshNormalHeader.h"
#import "MORefreshGifFooter.h"
#import "MODepthDoDetailViewController.h"
#import "MOOfficeTextSearchModel.h"
#import "MOMyShenPiWebViewViewController.h"

#define  SIZENUMBER            10
@interface MONoticeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,assign)NSInteger page;

@property(nonatomic,assign)NSInteger totalCount;

//请求参数
@property(nonatomic,strong)NSDictionary *postDic;
//
@property(nonatomic,assign)NSInteger countN;

@end

@implementation MONoticeViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self getNoNumber];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    switch ([self.typeStr integerValue]) {
        case 0:
            self.navigationItem.title = @"通知列表";
            break;
        case 1:
            self.navigationItem.title = @"待办列表";
            break;
        case 2:
            self.navigationItem.title = @"已办列表";
            break;
        case 3:
            self.navigationItem.title = @"查询列表";
            break;
        case 4:
            self.navigationItem.title = @"局内发布";
            break;
            
        default:
            break;
    }
    
    [self creatView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(downloadAfaterDataSource) name:@"officeTextStatusChange" object:nil];
}

-(void)creatView
{
    [self.view addSubview:self.tableView];
}


-(void)getNoNumber
{
    NSString *postUrl = [NSString stringWithFormat:@"%@?authorization=%@",ODPSCX_LOGIN_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    
    [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue]==0) {//成功
            
            UITabBarItem *item = self.tabBarController.tabBar.items[2];
            if ([responseObject[@"totalCount"] integerValue]>0) {
                if ([responseObject[@"totalCount"] integerValue]>99) {
                    item.badgeValue = @"99+";
                }else{
                    item.badgeValue = [NSString passNullForString:responseObject[@"totalCount"]];
                }
            }
        }
    } failure:^(NSError *error) {
    }];
}

#pragma mark -- 待办数据
-(void)requestData
{
    if ([self.typeStr integerValue]==0||[self.typeStr integerValue]==1) {//待办
        
        NSString *postUrl = [NSString stringWithFormat:@"%@/%ld/%ld?authorization=%@",ODPSDB_FINDDBLIST_URL,(long)self.page,self.page+SIZENUMBER,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
        
        [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
            NSLog(@"待办列表:%@",responseObject);
            [self refreshEnding];
            if ([responseObject[@"status"] integerValue]==1) {
                NSArray *arr = responseObject[@"wjList"];
                if (self.page==1) {
                    self.dataSource = [NSMutableArray array];
                }
                for (int i = 0; i<arr.count; i++) {
                    NSDictionary *dic = arr[i];
                    MONoticeModel *model = [[MONoticeModel alloc]init];
                    model.nameStr = dic[@"bt"];
                    model.dateStr = dic[@"ddsj"];
                    model.comeStr = dic[@"hjmc"];
                    model.comeNumberStr = dic[@"wh"];
                    model.typeStr = [dic[@"sfyy"] isEqualToString:@"是"]?@"1":@"0";
                    model.wdlx = [NSString passNullForString:dic[@"wdlx"]].length>0?[NSString passNullForString:dic[@"wdlx"]]:@"收文处理单";
                    model.key = dic[@"key"];
                    
                    [self.dataSource addObject:model];
                }
                if (arr.count==0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    [[ADShowMessage shareShowMessage] showTextOnly:@"暂无数据" showInView:self.view];
                }
            }
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            NSLog(@"待办列表:%@",[error localizedDescription]);
            [self refreshEnding];
            [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
        }];
        
    }else if ([self.typeStr integerValue]==2) {//已办
        
        NSString *postUrl = [NSString stringWithFormat:@"%@/%ld/%ld?authorization=%@",ODPSSUYB_FINDSUYBLIST_URL,(long)self.page,self.page+SIZENUMBER,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
        
        [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
            NSLog(@"已办列表:%@",responseObject);
            [self refreshEnding];
            if ([responseObject[@"status"] integerValue]==1) {
                NSArray *arr = responseObject[@"ybList"];
                if (self.page==1) {
                    self.dataSource = [NSMutableArray array];
                }
                for (int i = 0; i<arr.count; i++) {
                    NSDictionary *dic = arr[i];
                    MONoticeModel *model = [[MONoticeModel alloc]init];
                    model.nameStr = dic[@"bt"];
                    model.dateStr = dic[@"wcsj"];
                    model.comeStr = [NSString passNullForString:dic[@"hjmc"]];
                    model.comeNumberStr = [NSString passNullForString:dic[@"wh"]];
                    model.typeStr = [[NSString passNullForString:dic[@"sfyy"]] isEqualToString:@"是"]?@"1":@"0";
                    model.wdlx = [NSString passNullForString:dic[@"cllx"]];
                    model.key = [NSString passNullForString:dic[@"key"]];
                    
                    [self.dataSource addObject:model];
                }
                if (arr.count==0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    [[ADShowMessage shareShowMessage] showTextOnly:@"暂无数据" showInView:self.view];
                }
            }
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            NSLog(@"已办列表:%@",[error localizedDescription]);
            [self refreshEnding];
            [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
        }];
        
    }else if ([self.typeStr integerValue]==3){//公文查询
        
        NSString *url = [NSString stringWithFormat:@"%@?authorization=%@",ODPSCX_WJZHCXLIST_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
        
        MOOfficeTextSearchModel *model1 = self.searchConditionArray[0][0];
        MOOfficeTextSearchModel *model2 = self.searchConditionArray[1][0];
        MOOfficeTextSearchModel *model3 = self.searchConditionArray[1][1];
        MOOfficeTextSearchModel *model4 = self.searchConditionArray[1][2];
        MOOfficeTextSearchModel *model5 = self.searchConditionArray[2][0];
        MOOfficeTextSearchModel *model6 = self.searchConditionArray[3][0];
        
        self.postDic = @{
                              @"bt":model1.valueStr?model1.valueStr:@"",
                              @"wjz":model2.valueStr?model2.valueStr:@"",
                              @"wjnf":model3.valueStr?model3.valueStr:@"",
                              @"wjh":model4.valueStr?model4.valueStr:@"",
                              @"wjlx":model5.valueStr?model5.valueStr:@"",
                              @"zbbmmc":model6.valueStr?model6.valueStr:@""
                              };
        [PPNetworkHelper POST:url parameters:self.postDic success:^(id responseObject) {
            NSLog(@"公文查询：%@",responseObject);
            [self refreshEnding];
            if ([responseObject[@"status"] integerValue]==1) {
                NSArray *arr = responseObject[@"wjlist"];
                if (self.page==1) {
                    self.dataSource = [NSMutableArray array];
                }
                for (int i = 0; i<arr.count; i++) {
                    NSDictionary *dic = arr[i];
                    MONoticeModel *model = [[MONoticeModel alloc]init];
                    model.depthDo = @"3";
                    model.nameStr = dic[@"bt"];
                    model.dateStr = dic[@"ngsdrq"];
                    model.comeStr = [NSString passNullForString:dic[@"wh"]];
                    model.comeNumberStr = @"";
                    model.typeStr = [[NSString passNullForString:dic[@"sfyy"]] isEqualToString:@"是"]?@"1":@"0";
                    model.wdlx = [NSString passNullForString:dic[@"wdlx"]];
                    model.key = [NSString passNullForString:dic[@"key"]];
                    
                    [self.dataSource addObject:model];
                }
                if (arr.count==0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    [[ADShowMessage shareShowMessage] showTextOnly:@"暂无数据" showInView:self.view];
                }
            }
            [self.tableView reloadData];
            
        } failure:^(NSError *error) {
            NSLog(@"公文查询：%@",[error localizedDescription]);
            [self refreshEnding];
            [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:self.view];
        }];
        
        
    }else{//局内发布
        
        NSString *postUrl = [NSString stringWithFormat:@"%@/%ld/%ld?authorization=%@",JNFB_GETJNFBLIST_URL,(long)self.page,self.page+SIZENUMBER,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
        
        [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
            NSLog(@"局内发布:%@",responseObject);
            [self refreshEnding];
            if ([responseObject[@"code"] integerValue]==0) {
                NSArray *arr = responseObject[@"data"];
                if (self.page==1) {
                    self.dataSource = [NSMutableArray array];
                }
                for (int i = 0; i<arr.count; i++) {
                    NSDictionary *dic = arr[i];
                    MONoticeModel *model = [[MONoticeModel alloc]init];
                    model.depthDo = @"4";
                    model.nameStr = dic[@"title"];
                    model.content = dic[@"content"];
                    model.dateStr = dic[@"sendTime"];
                    model.fileList = dic[@"fileList"];
//                    model.dateStr = [NSString passNullForString:dic[@"sendUser"]];
//                    model.comeNumberStr = dic[@"sendTime"];
                    model.key = [NSString passNullForString:dic[@"wjKey"]];
                    
                    [self.dataSource addObject:model];
                }
                if (arr.count==0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    [[ADShowMessage shareShowMessage] showTextOnly:@"暂无数据" showInView:self.view];
                }
            }
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            NSLog(@"局内发布:%@",[error localizedDescription]);
            [self refreshEnding];
            [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
        }];
    }


}


#pragma mark -刷新，加载更多
//刷新
- (void)downloadAfaterDataSource{
    self.page = 1;
    [self requestData];
}

//加载更多
- (void)downloadBeforeDataSource{
    self.page+=SIZENUMBER+1;
    [self requestData];
}

//刷新效果停止
- (void)refreshEnding{
    [self.tableView.mj_footer endRefreshing];
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MONoticeViewCell *cell = [MONoticeViewCell cellWithTableView:tableView andIndexPath:indexPath];
    MONoticeModel *model = self.dataSource[indexPath.row];
    cell.model = model;
    
    __weak typeof  (self)weakself = self;
    cell.clickLongTapBlock = ^{
        [weakself clickLongTapAndTitle:model.nameStr];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [MONoticeViewCell heightForMONoticeViewCellAndModel:self.dataSource[indexPath.row]];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0001;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MONoticeModel *model = self.dataSource[indexPath.row];

    if ([self.typeStr integerValue]==0||[self.typeStr integerValue]==1) {//待办
        MOWaitDoDetailViewController *vc = [[MOWaitDoDetailViewController alloc]init];
        vc.waitModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([self.typeStr integerValue]==2){//已办
        if ([model.wdlx isEqualToString:@"公告审批表"]) {
            MODepthDoDetailViewController *vc = [[MODepthDoDetailViewController alloc]init];
            vc.waitModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            MOFinishDoDetailViewController *vc = [[MOFinishDoDetailViewController alloc]init];
            vc.waitModel = model;
            vc.typeStr = self.typeStr;
            vc.postDic = self.postDic;
            vc.searchConditionArray = self.searchConditionArray;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if([self.typeStr integerValue]==3){//查询
        
        NSString *url = [NSString stringWithFormat:@"%@?authorization=%@",ODPSCX_WJZHCXQUERYSWCLD_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
        
        NSMutableDictionary *muPostDic = [NSMutableDictionary dictionaryWithDictionary:self.postDic];
        [muPostDic setObject:model.key forKey:@"wjKey"];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [PPNetworkHelper GET:url parameters:muPostDic success:^(id responseObject) {
            NSLog(@"公文综合查询详情：%@",responseObject);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            if ([responseObject[@"status"] integerValue]==1) {
                model.wdlx = [NSString passNullForString:responseObject[@"data"][@"lx"]];
                //bllx
                if ([[NSString passNullForString:responseObject[@"data"][@"bllx"]] isEqualToString:@"待办"]) {
                    MOWaitDoDetailViewController *vc = [[MOWaitDoDetailViewController alloc]init];
                    vc.waitModel = model;
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    MOFinishDoDetailViewController *vc = [[MOFinishDoDetailViewController alloc]init];
                    vc.waitModel = model;
                    vc.typeStr = self.typeStr;
                    vc.postDic = responseObject[@"data"];
                    vc.searchConditionArray = self.searchConditionArray;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }else{
                [[ADShowMessage shareShowMessage]showTextOnly:responseObject[@"msg"] showInView:self.view];;
            }
        } failure:^(NSError *error) {
            [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:self.view];;
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }else{//局内发布
        MODepthDoDetailViewController *vc = [[MODepthDoDetailViewController alloc]init];
        vc.waitModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

#pragma mark - 设置顶头分割线
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        if (@available(iOS 8.0, *)) {
            [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        if (@available(iOS 8.0, *)) {
            [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

-(void)clickLongTapAndTitle:(NSString *)titleS
{
    if (self.countN>0) {
        return;
    }
    if ([self.typeStr integerValue]!=4) {
        return;
    }
    self.countN++;
    MOHintView *hintView = [[MOHintView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andContentStr:@"确认发起局内发布指派？"];
    __weak typeof (self)weakSelf = self;
    hintView.clickCancelButtonBlock = ^{
        weakSelf.countN = 0;
    };
    hintView.clickSureButtonBlock = ^{
        
        weakSelf.countN = 0;
        NSString *processKeyStr = @"KEY_publish";
        NSString *postUrl = [NSString stringWithFormat:@"%@?processKey=%@",STARTPROC_STARTPROCESS_URL,processKeyStr];
        [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
        [PPNetworkHelper POST:postUrl parameters:nil success:^(id responseObject) {
            NSLog(@"工单申请：%@",responseObject);
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            
            NSString *urlStr = [NSString stringWithFormat:@"%@/static/dynamic-form/show-page.html?staffId=%@&processDefinitionId=%@&proKey=%@",AD_HOME,[MOUser sharedMOUser].userName,responseObject,processKeyStr];
            if ([processKeyStr isEqualToString:@"KEY_publish"]) {
                urlStr = [NSString stringWithFormat:@"%@&jnTitle=%@",urlStr,titleS];
            }
            NSLog(@"%@",urlStr);
            MOMyShenPiWebViewViewController *vc = [[MOMyShenPiWebViewViewController alloc]init];
            __weak typeof (self)weakSelf = self;
            vc.commitEndBlock = ^{
                [weakSelf downloadAfaterDataSource];
            };
            vc.urlStr = urlStr;
            vc.titleStr = @"工单申请";
            [weakSelf.navigationController pushViewController:vc animated:YES];
            
        } failure:^(NSError *error) {
            NSLog(@"工单申请：%@",[error localizedDescription]);
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
            [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:weakSelf.view];
        }];
        
    };
    [WINDOW addSubview:hintView];
    
    
}

#pragma mark -懒加载
-(UITableView *)tableView
{
    if (!_tableView) {
        
        CGFloat H = 0;
        if ([self.typeStr integerValue]==0) {
            H = TabbarHeight;
        }else{
            H = 0;
        }
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-H-StatusBarAndNavigationBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        _tableView.mj_header = [MORefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downloadAfaterDataSource)];
        _tableView.mj_footer = [MORefreshGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(downloadBeforeDataSource)];
        [_tableView.mj_header beginRefreshing];
        
    }
    return _tableView;
}


@end
